package com.zdx.yswl.ui.task;

import java.io.IOException;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.zdx.yswl.App;
import com.zdx.yswl.Constant;
import com.zdx.yswl.asynctask.BaseHttpTask;
import com.zdx.yswl.base.KException;
import com.zdx.yswl.tool.KStringTool;
import com.zdx.yswl.ui.exception.JSONParseException;
import com.zdx.yswl.ui.exception.NetworkException;
import com.zdx.yswl.ui.http.HttpUtils;
import com.zdx.yswl.view.dialog.LoadingProgressDialog;

public class LoginTask extends BaseHttpTask<Map<String, Object>, Void, Object> {
	private LoadingProgressDialog progressDialog;
	private Context context;
	
	public LoginTask(Context context,int taskId, TaskDelegate delegate) {
		super(taskId, delegate);
		this.context = context;
	}

	/**
	 * 首先执行该方法，在真正的后台操作前北UI线程调用，可在该方法内执行一些准备工作，如：进度条或控件的实例化
	 */

	protected void onPreExecute() {
		super.onPreExecute();
		startProgressDialog();
	}
	
	@Override
	protected Object doInBackground(Map<String, Object>... params) {
		
		String str = "";
		try {
			str = HttpUtils.sendPostMethod4Path(Constant.ConfigNet.user_login, params[0], "utf-8");
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return new NetworkException();
		} catch (IOException e) {
			e.printStackTrace();
			return new NetworkException();
		}
		
		return str;
	}


	@Override
	protected void onPostExecute(Object result) {
		super.onPostExecute(result);
		stopProgressDialog();
		
		if (result instanceof NetworkException) {
			if (super.getDelegate() != null) {
				super.getDelegate().faild_TaskDelegate(super.getTaskId(), result);
			}
			return;
		}
		
		
		JSONObject json = null;
		try {
			json = new JSONObject(result+"");
			int __returnCode = json.getInt("status");
			if (__returnCode != 0) {
				if (this.getDelegate() != null) {
					this.getDelegate() .faild_TaskDelegate(super.getTaskId(), new KException(json.getString("msg")));
				}
				return;
			}
			
			String userId = json.getString("data");
			if (KStringTool.isNotEmpty(userId)) {
				App.getInstance().recordUserId(context, userId);
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
			if (super.getDelegate() != null) {
				super.getDelegate().faild_TaskDelegate(super.getTaskId(), new JSONParseException());
			}
			return;
		}
		
		this.getDelegate().success_TaskDelegate(super.getTaskId(),null );
		
	}
	

	/**
	 * 用户取消线程时调用
	 */
	protected void onCancelled() {
		super.onCancelled();
		stopProgressDialog();
	}
	
	
	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = LoadingProgressDialog.createDialog(context);
			progressDialog.setMessage("正在加载...");
			progressDialog.setCancelable(true);
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
}
